﻿using System;
using System.Runtime.InteropServices;

namespace WiMo.Games.StandardInput.Accelerometer
{

    class SamsungGSensor : IGSensor
    {
     
        public struct Vector
        {
            public float x;
            public float y;
            public float z;
        }

        public enum SmiResultCode
        {
            Success = 0x00000000,
            Unknown = 0x00000001,
            DeviceNotFound = 0x00000002,
            DeviceDisabled = 0x00000003,
            PermissionDenied = 0x00000004,
            InvalidParameter = 0x00000005,
            CannotActivateServer = 0x00000006,

            HapticsInvalidHandle = 0x10020000,
            HapticsOutOfHandles = 0x10020001,

            LedColorNotSupported = 0x10030000

        }


        /*public struct SdkVersion
        {
            public uint major;
            public uint minor;
            public uint patch;
        }*/

        public delegate void EventHandler(Vector v);

  //      public const string SamsungMobileSDKDllName = "SamsungMobileSDK_1.dll";
        public const string SamsungMobileSDKDllName = "SamsungMobileSDK_2.dll";


        //[DllImport(SamsungMobileSDKDllName, EntryPoint = "SmiGetSdkVersion")]
        //private static extern IntPtr SmiGetSdkVersion(ref SdkVersion version);

        [DllImport(SamsungMobileSDKDllName, EntryPoint = "SmiAccelerometerGetVector")]
        private static extern SmiResultCode GetVector(ref Vector accel);

        /*[DllImport(SamsungMobileSDKDllName, EntryPoint = "SmiAccelerometerGetCapabilities")]
        private static extern SmiResultCode GetCapabilities(ref Capabilities cap);

        [DllImport(SamsungMobileSDKDllName, EntryPoint = "SmiAccelerometerRegisterHandler")]
        private static extern SmiResultCode RegisterHandler(uint period, EventHandler handler);

        [DllImport(SamsungMobileSDKDllName, EntryPoint = "SmiAccelerometerUnregisterHandler")]
        private static extern SmiResultCode UnregisterHandler();*/


        public static SamsungGSensor Create()
        {
            Vector vec = new Vector();
            if (GetVector(ref vec) != SmiResultCode.Success)
                throw new Exception("No Omnia G-Sensor found");
            return new SamsungGSensor();
        }

        private SamsungGSensor()
        {
        }

        public Vector3 GetGVector()
        {
            Vector newVec = new Vector();
            GetVector(ref newVec);
            var ret = new Vector3();
            ret.X = newVec.x;
            ret.Y = newVec.y;
            ret.Z = -newVec.z;
            //double samsungScaleFactor = 1.0 / 1000.0 * 9.8 * 3.3793103448275862068965517241379;
            var samsungScaleFactor = 7.8f;
            return ret.Scale(samsungScaleFactor);
        }
  
        public void Dispose()
        {
        }

    }
}